//
//  HYFComposeView.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/7/28.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

import UIKit
import pop

class HYFComposeView: UIView {
    
    //记录 mainVc
    var target:UIViewController?
    
    //保存 compose 数组
    lazy var composeButtonInfo:[HYFComponseButtonInfo] = [HYFComponseButtonInfo]()

    //保存按钮数组
    lazy var buttons:[HYFComposeButton] = [HYFComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: SCREENH))
        
        setupUI()
        
      
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        //        backgroundColor = RandomColor()
        //        let image = getScreenShot()
        //        let data = UIImagePNGRepresentation(image)
        //        data?.writeToFile("/Users/teacher/Desktop/哈哈.png", atomically: false)
      
        //添加控件
        addSubview(bgImageView)
        addSubview(logoImageView)
        
        addChildButtons()
        
        logoImageView.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
            
        }
        
        bgImageView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
    }
    
    //监听方法
    func buttonClick(button:HYFComposeButton){
        
       //设置动画
        UIView.animateWithDuration(0.25, animations: { 
            
            //遍历保存数据按钮
            for value in self.buttons{
                
                //设置透明度
                value.alpha = 0.2
                //判断是不是当前点击的按钮
                if value == button {
                    
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            
            }) { (_) in
                
                UIView.animateWithDuration(0.25, animations: { 
                    
                    for value in self.buttons {
                        
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
 
                    }, completion: { (_) in
                        
                        guard let vcName = button.componseInfo?.nextvc else{
                            
                            return
                        }
                        
                        
                        guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                            
                            return
                        }
                        
                        
                        print(NSClassFromString("\(pn).\(vcName)"))
                        //判断 class 是否为 nil
                        guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else{
                            
                            return
                        }
                        
                        let tempVc = cn.init()
                        let naVc = UINavigationController(rootViewController: tempVc)
                        
                        self.target?.presentViewController(naVc, animated: true, completion: { 
                            
                            self.removeFromSuperview()
                        })
                })
        }
        
    }
    
    //添加 composeView
    func composeViewShow(target:UIViewController){
        
        target.view.addSubview(self)
        
        self.target = target
        
        setupButtonAnim(true)
    }
    
    func addChildButtons(){
        
        //给数组赋值
        composeButtonInfo = getComposeButtonInfos()
        
        let childW:CGFloat = 80
        let childH:CGFloat = 110
        
        //按钮间距
        let childMargin:CGFloat = (SCREENW - 3 * childW)/4
        
        for (i,value) in composeButtonInfo.enumerate(){
            
         //得到行数和列数
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            
            let button = HYFComposeButton()
            //给 button 的属性赋值
            button.componseInfo = value
            
            button.setImage(UIImage(named: value.icon ?? ""), forState: .Normal)
            button.setTitle(value.title, forState: .Normal)
            button.frame = CGRect(x: childMargin + (childW + childMargin) * col , y: (childH + childMargin) * row + SCREENH, width: childW, height: childH)
            
            addSubview(button)
            //添加点击事件
            button.addTarget(self, action: #selector(HYFComposeView.buttonClick(_:)), forControlEvents: .TouchUpInside)
            
            //添加按钮
            buttons.append(button)
        }
    }
    
    //返回button数组
    func getComposeButtonInfos()->[HYFComponseButtonInfo]{
        
        //获取路径
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        //读取文件到数组
        let array = NSArray(contentsOfFile: file)!
        //创建一个可变的临时数组
        var tempArray:[HYFComponseButtonInfo] = [HYFComponseButtonInfo]()
        //遍历 array 字典转模型
        for dic in array {
            
            //创建模型
            let componseButtonInfo = HYFComponseButtonInfo(dict: dic as! [String : AnyObject])
            //添加模型
            tempArray.append(componseButtonInfo)
        }
        
        return tempArray
    }
    

    //点击屏幕,消失
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        setupButtonAnim(false)

        //延迟删除当前view
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }

    }
    
    func setupButtonAnim(isUp:Bool){
        
        //距离
        let margin:CGFloat = isUp ? -350 : 350
        //数组集合
        let set = isUp ? buttons.enumerate() :buttons.reverse().enumerate()
        
        for (i ,value) in set {
            
            //遍历按钮数组,分别设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //设置 toValue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            //开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //弹性系数
            anim.springBounciness = 10
            //动画速度
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
            
        }
    }
    

    //懒加载控件
    private lazy var bgImageView:UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    private lazy var logoImageView:UIImageView = UIImageView(imgName:"compose_slogan")
}
